﻿// --------------
// 作者:Vitity
// --------------

namespace NICWebApi.Extensions.RESTfulResult.Filter;

/// <summary>
/// Swagger文档枚举字段显示过滤器
/// </summary>
public class EnumSchemaFilter : ISchemaFilter
{
    /// <summary>
    /// 应用枚举架构过滤器
    /// </summary>
    /// <param name="schema">OpenAPI架构</param>
    /// <param name="context">架构过滤器上下文</param>
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (!context.Type.IsEnum) return;

        schema.Enum.Clear();
        schema.Type = "string";
        schema.Format = null;

        var enumDescriptions = new StringBuilder();
        foreach (var enumName in Enum.GetNames(context.Type))
        {
            var enumValue = (Enum)Enum.Parse(context.Type, enumName);
            var description = GetEnumDescription(enumValue);
            var enumIntValue = Convert.ToInt64(enumValue);

            schema.Enum.Add(new OpenApiString(enumName));
            enumDescriptions.AppendLine(
                $"【枚举：{enumName}{(description is null ? string.Empty : $"({description})")}={enumIntValue}】");
        }
        schema.Description = enumDescriptions.ToString();
    }

    /// <summary>
    /// 获取枚举描述特性值
    /// </summary>
    private static string? GetEnumDescription(Enum value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());
        var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
        return attributes.Length > 0 ? attributes[0].Description : null;
    }
}